package com.mzy.basics.reflectionDemo.newReflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/6/14 16:28
 * @Version 1.0
 */
public class MyUtil {

    /**
     * 精彩：
     * Class.getField和getDeclaredField的区别
     * @param args
     */

    /**
     * getField
     * 获取一个类的 ==public成员变量，包括基类== 。
     * getDeclaredField
     * 获取一个类的 ==所有成员变量，不包括基类== 。
     * Field.setAccessible
     * 成员变量为private，必须进行此操作。
     *
     * @param args
     */
    public static void main(String[] args) {
        testFields();
    }

    public static void testFields() {
        try {
            // 补充
            Class<?> aClass = Dog.class.getClass();
            Field color = aClass.getDeclaredField("name");
            Object type = color.getType();
            System.out.println(type);
            System.out.println("---------------------------   ");

            System.out.println("Declared fields: ");
            Field[] fields = Dog.class.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                System.out.println(fields[i].getName()); // 此处结果是color, name, type, fur
            }

            System.out.println("Public fields: ");
            fields = Dog.class.getFields();
            for (int i = 0; i < fields.length; i++) {
                System.out.println(fields[i].getName()); // 此处结果是color, location
            }

            Dog dog = new Dog();
            dog.setAge(1);
            Method method = dog.getClass().getMethod("getAge", null);
            Object value = method.invoke(dog);
            System.out.println(value); // 此处结果是1
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class Dog extends Animal {
    public int color;
    protected int name;
    private int type;
    int fur;
}

class Animal {
    public int location;
    protected int age;
    private int height;
    int length;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}